<template>
  <div>
<div class="search">
  <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音">
</div>
  <div
    v-show="keyword"
    class="search-content" ref="search">
    <ul>
      <li class="search-item border-topbottom" v-for="item in list" :key="item.id" @click="handleCityClick(item.name)">
        {{item.name}}
      </li>
      <li class="search-item border-topbottom" v-show="hasNoData">
        没有找到匹配数据
      </li>
    </ul>
  </div>
  </div>
</template>
<script type="text/ecmascript-6">
  import Bscroll from 'better-scroll'
export default{
  data:function(){
    return {
      keyword:'',
      list:[],
      timer:null
    }
  },
  mounted:function(){
    this.scroll = new Bscroll(this.$refs.search)
  },
  computed:{
    hasNoData:function(){
      return !this.list.length;
    }
  },
  methods:{
    handleCityClick:function(city){
      //派发一个叫changeCity的action
      //this.$store.dispatch('changeCity', city);
      //直接调用mutation
      this.$store.commit('changeCity', city);
      this.$router.push('/');
    }
  },
  watch:{
    keyword: function(){
      var that =this;
      if(this.timer){
        clearTimeout(this.timer)
      }
      if(!this.keyword){
        this.list = [];
        return;
      }
      this.timer = setTimeout(()=>{
        var result = [];
        for(let i in this.cities){
          this.cities[i].forEach(function(val){
            if(val.spell.indexOf(that.keyword) > -1 || val.name.indexOf(that.keyword) > -1){
              result.push(val);
            }
          })
        }
        this.list = result;
      },100)
    }
  },
  props:['cities']
}
</script>
<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .search
    height:0.72rem;
    padding: 0 0.1rem;
    background: $bgColor;
    .search-input
      box-sizing border-box;
      padding: 0 0.1rem;
      height: 0.62rem;
      line-height:0.62rem;
      text-align center;
      border-radius 0.06rem;
      width:100%;
      color:#666;
  .search-content
      position: absolute;
      overflow: hidden;
      z-index :1;
      right:0;
      left:0;
      top:1.58rem;
      background: #eee;
      bottom:0;
     .search-item
       line-height:0.62rem;
       padding-left:0.2rem;
       color:#666;
       background:#fff;
</style>
